package com.zipeng.system.sys.controller;

import com.zipeng.jwt.JwtUtils;
import com.zipeng.result.ResultUtils;
import com.zipeng.result.ResultVo;
import com.zipeng.system.sys.entity.TokenVo;
import io.jsonwebtoken.Jwts;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@Slf4j
@RestController
@RequestMapping("/api/sys")
public class SysController {
    @Autowired
    private JwtUtils jwtUtils;
    @PostMapping(value = "/refreshToken")
    public ResultVo refreshToken(@RequestBody  TokenVo tokenVo){
        String reToken = "";
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        UserDetails details = (UserDetails) authentication.getPrincipal();
        //验证原来的token是否合法
        Boolean aBoolean = jwtUtils.validateToken(tokenVo.getToken(), details);
        if(aBoolean){
            //生成新的token
            reToken = jwtUtils.refreshToken(tokenVo.getToken());
        }
        //取出本次token到期的时间,返回前端做判断
        long expireTime = Jwts.parser()   //得到DefaultJwtParser
                .setSigningKey(jwtUtils.getSecret())  //设置签名的秘钥
                .parseClaimsJws(reToken.replace("jwt_", ""))
                .getBody().getExpiration().getTime();
        TokenVo vo = new TokenVo();
        vo.setToken(reToken);
        vo.setExpireTime(expireTime);
        return ResultUtils.success("生成token成功!",vo);
    }
}
